package me.zhengjie.modules.common.service.impl;

import me.zhengjie.modules.common.domain.TAttachment;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.common.repository.TAttachmentRepository;
import me.zhengjie.modules.common.service.TAttachmentService;
import me.zhengjie.modules.common.service.dto.TAttachmentDTO;
import me.zhengjie.modules.common.service.dto.TAttachmentQueryCriteria;
import me.zhengjie.modules.common.service.mapper.TAttachmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author sw
* @date 2019-08-21
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TAttachmentServiceImpl implements TAttachmentService {

    @Autowired
    private TAttachmentRepository tAttachmentRepository;

    @Autowired
    private TAttachmentMapper tAttachmentMapper;

    @Override
    public Object queryAll(TAttachmentQueryCriteria criteria, Pageable pageable){
        Page<TAttachment> page = tAttachmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tAttachmentMapper::toDto));
    }

    @Override
    public Object queryAll(TAttachmentQueryCriteria criteria){
        return tAttachmentMapper.toDto(tAttachmentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TAttachmentDTO findById(Integer id) {
        Optional<TAttachment> tAttachment = tAttachmentRepository.findById(id);
        ValidationUtil.isNull(tAttachment,"TAttachment","id",id);
        return tAttachmentMapper.toDto(tAttachment.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TAttachmentDTO create(TAttachment resources) {
        return tAttachmentMapper.toDto(tAttachmentRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TAttachment resources) {
        Optional<TAttachment> optionalTAttachment = tAttachmentRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTAttachment,"TAttachment","id",resources.getId());

        TAttachment tAttachment = optionalTAttachment.get();
        // 此处需自己修改
        resources.setId(tAttachment.getId());
        tAttachmentRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        tAttachmentRepository.deleteById(id);
    }
}